<template>
  <div class="app-container search-list">
    <!-- PC端表格视图 -->
    <div v-if="!isMobile">
      <table-pagination
          :showOperatingButton="true"
          ref="el-search-table"
          :fetch="getData"
          type="remote"
          :adaptive="fixOption"
          :page-sizes="[20, 50, 100]"
          :columns="columns"
          :form-options="formOptions"
          list-field="records"
          total-field="totalElements"
          page-index-key="page"
          page-size-key="pageSize"
          height="300"
          method="get">
        <template slot="button">
          <el-radio-group v-model="formParams.status" @change="changeStatusRadio" size="mini">
            <el-radio-button label="">所有状态</el-radio-button>
            <!--          <el-radio-button :label="-1">预下单</el-radio-button>-->
            <!--          <el-radio-button :label="1">待支付</el-radio-button>-->
            <el-radio-button :label="2">待发货</el-radio-button>
            <el-radio-button :label="4">待收货</el-radio-button>
            <el-radio-button :label="3">已完成</el-radio-button>
          </el-radio-group>
          <div style="display: flex;align-items: flex-start">
            <upload-file
                :headers="headers"
                style="margin-left: 10px;margin-right: 10px"
                :fileType="['doc', 'pdf']"
                type="file"
                :drag="true"
                show-text="批量上传物流单号"
                :showFileList="true"
                accept=".xlsx"
                :isShowTip="true"
                :lazy="true"
                :responseFn="handleResponse"
                :action="uploadPath"
                title="选择文件"
                v-model="importProductsFileName"
            ></upload-file>
            <el-button type="primary" size="mini" @click="settingVisible = true">导出订单</el-button>
          </div>
        </template>
        <template slot="statusText" slot-scope="{row}">
          <el-link :underline="false" :type="storeMap(row.statusText)" plain size="mini">{{ row.statusText }}</el-link>
        </template>
        <template slot="confirmEmail" slot-scope="{row}">
          <el-link :underline="false" :type="row.confirmEmail ? 'primary' : 'danger'" plain size="mini">
            {{ row.confirmEmail ? '已发送' : '未发送' }}
          </el-link>
        </template>
        <template slot="logisticsStatusText" slot-scope="{row}">
          <el-link :underline="false" :type="storeMap(row.logisticsStatusText)" plain size="mini">
            {{ row.logisticsStatusText }}
          </el-link>
        </template>
        <el-table-column label="订单号" slot="append" width="180px" fixed='left' align='left'>
          <template slot-scope="{row}">
            <a style="color: #1A89FF" @click="handleDetail(row.id)">{{ row.orderNumber }}</a>
          </template>
        </el-table-column>
        <el-table-column label="操作" slot="append" width="130px">
          <template slot-scope="scope">
            <el-button plain size="mini" type="primary"
                      @click="handleConfirmEmail(scope.row.id)">发送确认邮件
            </el-button>
          </template>
        </el-table-column>
      </table-pagination>
    </div>

    <!-- 移动端列表视图 -->
    <mobile-order-list v-else :siteId="siteId" />

    <el-dialog :visible.sync="settingVisible" title="订单导出" width="400px">
      <div class="desc">
        <div class="export" style="text-align: left;">
          <header>导出范围</header>
          <section>
            <div class="orca-row orca-form-item">
              <el-radio v-model="exportType" label="all" style="margin-bottom: 15px">所有订单</el-radio>
              <el-radio v-model="exportType" label="filter">符合当前筛选条件的订单</el-radio>
            </div>
          </section>
        </div>
        <div style="margin-top: 20px">
          <el-button type="primary" @click="handleExport" :loading="submitLoading">
            {{ submitLoading ? '导出中' : '导出' }}
          </el-button>
          <el-button @click="settingVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getToken} from '@/utils/auth';
import uploadFile from '@/components/Upload/uploadFile';
import TablePagination from '_c/Tables/table-pagination';
import MobileOrderList from '@/components/MobileOrderList';
import {getOrderPage, exportOrder, confirmEmail} from '@/api/order';
import {currency, utcFormat} from '@/utils/filters';
import {mapGetters} from 'vuex';
import axios from 'axios';

export default {
    name: 'order-list',
    components: {
        uploadFile,
        TablePagination,
        MobileOrderList
    },
    data () {
        return {
            importProductsFileName: '',
            headers: {'X-TULIANG-Session-Token': getToken()},
            submitLoading: false,
            exportType: 'all',
            settingVisible: false,
            fixOption: {fixedHeader: true},
            formParams: {
                status: '',
                payStatus: '',
                logisticsStatus: '',
                orderNumber: '',
                email: '',
                startTime: '',
                endTime: '',
                page: 1,
                pageSize: 20
            },
            formOptions: {
                showResetBtn: true,
                showSearchBtn: true,
                inline: false,
                submitBtnText: '查询',
                size: 'small',
                labelWidth: 120,
                resetBtnCallback: () => {
                    this.formParams = {
                        ...this.formParams,
                        ...{
                            status: '',
                            payStatus: '',
                            logisticsStatus: '',
                            orderNumber: '',
                            email: '',
                            startTime: '',
                            endTime: '',
                            page: 1,
                            pageSize: 20
                        }
                    };
                    this.$refs['el-search-table'].resetFields();
                    this.$refs['el-search-table'].fetchHandler(this.formParams, false);
                },
                forms: [
                    {prop: 'orderNumber', label: '订单号：', placeholder: '请输入订单号'},
                    {prop: 'email', label: '邮箱：', placeholder: '请输入邮箱'},
                    {
                        prop: 'logisticsStatus',
                        label: '物流状态：',
                        itemType: 'select',
                        placeholder: '请选择物流状态',
                        options: [
                            {value: '', label: '所有状态'},
                            {value: 1, label: '待发货'},
                            {value: 2, label: '部分发货'},
                            {value: 3, label: '全部发货'},
                            {value: 4, label: '全部确认'}
                        ]
                    },
                    {
                        prop: ['startTime', 'endTime'],
                        label: '下单时间：',
                        itemType: 'daterange',
                        startPlaceholder: ' 开始日期',
                        endPlaceholder: ' 结束日期'
                    }
                ]
            },
            columns: [
                {label: '下单邮箱', prop: 'email', showOverflowTooltip: true},
                {
                    label: '订单金额',
                    prop: 'payAmount',
                    render: row => {
                        if (row.payAmount) {
                            return currency(row.payAmount, row.currencySymbol || '$');
                        }
                        return '';
                    }
                },
                {
                    label: '下单时间',
                    prop: 'createDate',
                    render: row => {
                        return utcFormat(row.createDate, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
                    },
                    width: '180px'
                },
                {label: '商品数', prop: 'totalItemNum'},
                {label: '支付方式', prop: 'payType'},
                {label: '支付状态', prop: 'payStatusText'},
                {label: '订单状态', prop: 'statusText', slotName: 'statusText'},
                {label: '物流状态', prop: 'logisticsStatusText', slotName: 'logisticsStatusText'},
                // { label: '订单来源', prop: 'orderSource' },
                {label: '国家/地区', prop: 'country', showOverflowTooltip: true},
                {label: '确认邮件', prop: 'confirmEmail', slotName: 'confirmEmail'}
            ]
        };
    },
    computed: {
        ...mapGetters([
            'timeZone',
            'siteList',
            'isMobile' // 从 Vuex store 获取移动设备状态
        ]),
        siteId () {
            return this.$store.state.user.siteId;
        },
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        exportPath () {
            return `${process.env.VUE_APP_BASE_API}/order/export`;
        },
        uploadPath () {
            return process.env.VUE_APP_BASE_API + '/paypal/tracking';
        }
    },
    methods: {
        storeMap (type) {
            // console.log(type);
            const status = new Map([
                ['待发货', 'warning'],
                ['待收货', 'primary'],
                ['已完成', 'success'],
                ['全部发货', 'info'],
                ['全部确认', 'success']
            ]);
            return status.get(type);
        },
        changeStatusRadio () {
            this.$refs['el-search-table'].fetchHandler(this.formParams.status, false);
        },
        getData (params) {
            this.formParams.siteId = this.siteId;
            params.startTime = this.getSiteTimeZoneStartTime(params.startTime);
            params.endTime = this.getSiteTimeZoneEndTime(params.endTime);
            params.status = this.formParams.status;
            this.formParams = {...this.formParams, ...params};
            return new Promise((resolve, reject) => {
                getOrderPage(this.formParams).then((res) => {
                    resolve(res);
                });
            });
        },
        handleDetail (id) {
            this.$router.push({name: 'order-detail', params: {id}});
        },
        handleConfirmEmail (id) {
            confirmEmail(id).then((res) => {
                if (res.code === '200') {
                    this.$refs['el-search-table'].loading = true;
                    setTimeout(() => {
                        this.$refs['el-search-table'].loading = false;
                        this.$message.success('发送成功');
                        this.formParams = {
                            ...this.formParams,
                            ...{
                                status: '',
                                payStatus: '',
                                logisticsStatus: '',
                                orderNumber: '',
                                email: '',
                                startTime: '',
                                endTime: '',
                                page: 1,
                                pageSize: 20
                            }
                        };
                        this.$refs['el-search-table'].resetFields();
                        this.$refs['el-search-table'].fetchHandler(this.formParams, false);
                    }, 3200);
                }
            });
        },
        getSiteTimeZoneStartTime (startTime) {
            if (startTime === undefined || startTime == null || startTime === '') {
                return startTime;
            }
            let tempTime = new Date(startTime);
            let month = (tempTime.getMonth() + 1 + 100).toString().substr(1);
            let date = (tempTime.getDate() + 100).toString().substr(1);
            let timeZoneStr = [tempTime.getFullYear(), month, date].join('/') + ' 00:00:00 UTC' + this.timeZone;
            return new Date(timeZoneStr).getTime();
        },
        getSiteTimeZoneEndTime (endTime) {
            if (endTime === undefined || endTime == null || endTime === '') {
                return endTime;
            }
            let tempTime = new Date(endTime);
            let month = (tempTime.getMonth() + 1 + 100).toString().substr(1);
            let date = (tempTime.getDate() + 100).toString().substr(1);
            let timeZoneStr = [tempTime.getFullYear(), month, date].join('/') + ' 23:59:59 UTC' + this.timeZone;
            return new Date(timeZoneStr).getTime();
        },
        downloadURL (data) {
            const blob = new Blob([data], {type: 'application/vnd.ms-excel'});
            console.log(blob);
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = '订单列表' + '_' + this.siteId + '_' + new Date().getTime().toString() + (Math.random().toFixed(2) * 400 + 100).toString() + '.xlsx';
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
        },
        handleExport () {
            this.submitLoading = true;
            let params = {siteId: this.siteId};
            params = this.exportType === 'all' ? params : Object.assign(params, this.formParams);
            axios({
                method: 'get',
                params,
                url: this.exportPath,
                headers: {
                    'X-TULIANG-Session-Token': getToken()
                },
                responseType: 'arraybuffer'
            }).then(res => {
                this.downloadURL(res.data);
                this.submitLoading = false;
            });
        },
        handleResponse (response, file, fileList) {
            // this.pageParams.page = 1;
            // this.getData(this.pageParams);
            return response;
        }
    }
};
</script>

<style scoped lang="scss">
.search-list {
  h4 {
    border-bottom: 1px solid #E8E8E8;
    margin: 0;
    margin-bottom: 10px;
    padding-bottom: 10px;
  }
}

.desc {
  font-size: 14px;
  color: #7e849c;
  margin-bottom: 0;

  .export {
    position: relative;

    header {
      padding-bottom: 20px;
      font-size: 16px;
      color: #30354d;
    }

    .orca-row {
      display: flex;
      flex-direction: column;
    }
  }
}

/* 移动端样式 */
@media screen and (max-width: 768px) {
  .app-container {
    padding: 10px !important;
  }

  .el-dialog {
    width: 90% !important;
    margin-top: 20vh !important;
  }
}
</style>
